package com.ruoyi.framework.interceptor.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SpokenTeacher;
import com.ruoyi.system.domain.SpokenUser;
import com.ruoyi.system.service.ISpokenTeacherService;
import com.ruoyi.system.service.ISpokenUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户已被禁用
 */
@Component
public class UserBanInterceptor implements HandlerInterceptor {

    @Autowired
    ISpokenUserService spokenUserService;

    @Autowired
    ISpokenTeacherService teacherService;

    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginUser loginUser = tokenService.getLoginUser(request);
        // 未登录 ||  // 系统用户 直接放行
        if(loginUser == null ||  loginUser.getUser().getUserType().equals("00")){
            return true;
        }
        Long userId = loginUser.getUserId();
        String userType = loginUser.getUser().getUserType();
        // 小程序用户
        if(userType.equals("01")){
            SpokenUser spokenUser = spokenUserService.selectById(userId);
            // 被禁用
            if(spokenUser.getSysUser().getStatus().equals("1")){
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.IS_BAN, "当前用户已被停用，请联系管理员")));
                return false;
            }
        }
        // 教师
        else if(userType.equals("02")){
            SpokenTeacher spokenTeacher = teacherService.selectById(userId);
            if(spokenTeacher.getSysUser().getStatus().equals("1")){
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.IS_BAN, "The current user has been disabled. Please contact the administrator")));
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
